
package jfireeagle.examples.swing;

import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import jfireeagle.FireEagleClient;
import jfireeagle.UserAuthorizationRequiredException;

public abstract class AbstractForm extends AbstractPanel
{
	protected JPanel fieldPanel;
	protected JButton submit;
	protected JButton clear;
	protected JPanel submitPanel;
	
	public AbstractForm(FireEagleClient c, int fieldCount)
	{
		super(c);
		
		this.setLayout(new BorderLayout());
		
		submitPanel = createSubmitPanel();
		
		if (fieldCount > 0)
		{
			fieldPanel = createFieldPanel(fieldCount);
		
			this.add(BorderLayout.CENTER, fieldPanel);
			this.add(BorderLayout.SOUTH, submitPanel);
		}
		else
		{
			this.add(BorderLayout.NORTH, submitPanel);
		}
		
		
		
		
	}
	
	protected JPanel createSubmitPanel()
	{
		JPanel pan = new JPanel();
		pan.setLayout(new FlowLayout());
		
		submit = new JButton("Submit");
		submit.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent e)
			{
				submit();
			}
			
		});
		
		pan.add(submit);
		
		clear = new JButton("Clear");
		clear.addActionListener(new ActionListener()
		{

			public void actionPerformed(ActionEvent e)
			{
				clear();
			}
			
		});
		
		pan.add(clear);
		
		return pan;
	}
	
	protected JPanel createFieldPanel(int fieldCount)
	{
		JPanel pan = new JPanel();
		pan.setLayout(new GridLayout(fieldCount, 2));
		return pan;
	}
	
	public final Object submit()
	{
		try
		{
			return onSubmit();
		}
		catch (UserAuthorizationRequiredException ex)
		{
			onException(ex);
		}
		return null;
	}

	protected void onException(UserAuthorizationRequiredException ex)
	{
		JOptionPane.showInputDialog(null, "Authorization required: " + ex.getUrl(), ex.getUrl());
	}
	
	public final void clear()
	{
		onClear();
	}

	abstract protected Object onSubmit();

	protected void onClear()
	{
		Component[] components = fieldPanel.getComponents();
		
		for (Component c : components)
		{
			if (c instanceof JTextField)
			{
				JTextField f = (JTextField) c;
				f.setText("");
			}
		}
		
	}
	
	protected void addField(String label, Component c)
	{
		fieldPanel.add(new JLabel(label));
		fieldPanel.add(c);
	}
	
	
}
